<template>
  <div class="list-page">
    <el-card class="card-box minh100">
      <template #header>
        <div class="card-box-header">
          <span
            @click="goBack"
            style="
              color: #5298ff;
              margin-left: 10px;
              margin-right: 10px;
              cursor: pointer;
            "
            >返回</span
          >
          <span>项目阶段概览</span>
        </div>
      </template>
      <el-collapse-transition>
        <div>
          <div class="stage-box">
            <template v-for="(item, index) in stageList" :key="index">
              <div
                class="text-box"
                :class="{
                  active: activeStage === index,
                  hasState: item.completePercent,
                  complete: item.completePercent == 100
                }"
                @click="handleChange(item, index)"
              >
                <div class="p-box">
                  <p>{{ item.completePercent || 0 }}</p>
                  <span>%</span>
                </div>

                <div class="status-box">
                  <!-- <template v-if="item.completePercent">
                    <SvgIcon
                      v-if="item.completePercent == 100"
                      name="wancheng"
                      size="24"
                    />
                    <SvgIcon v-else name="jinhang" size="24" />
                  </template>  -->
                  <!-- <SvgIcon v-else name="jinhang" size="24" /> -->
                  <span class="text">{{ item.projectStageName }}</span>
                </div>
              </div>
              <div
                class="arrow-box"
                :class="{ hide: index === stageList.length - 1 }"
              >
                <i class="icon snowfont icon-jindu" />
                <i class="icon snowfont icon-jindu" />
                <i class="icon snowfont icon-jindu" />
                <i class="icon snowfont icon-jindu" />
                <i class="icon snowfont icon-jindu" />
              </div>
            </template>
          </div>
          <p class="sub-title mt20" style="margin-bottom: 16px"></p>
          <el-table
            :data="tableData"
            stripe
            v-loading="loading"
            :header-cell-style="{
              background: '#F7F9FD',
              color: '#000000',
              height: '48px'
            }"
            class="btm-table"
            :row-class-name="tableRowClassName"
          >
            <template #empty>
              <el-empty :image-size="150" description="暂无数据"></el-empty>
            </template>
            <!-- <el-table-column type="index" label="序号" width="50">
              <template v-slot="scope">
                <span>{{
                  (item.pageNum - 1) * item.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column> -->
            <el-table-column prop="status" label="状态" width="80">
              <template #default="{ row }">
                <span style="display: flex; align-items: center">
                  <SvgIcon
                    :name="
                      !row.nodeStatusCode
                        ? 'shenpi-daipi'
                        : row.nodeStatusCode === 'end'
                        ? 'shenpi-wancheng'
                        : 'shenpi-jinhang'
                    "
                    :size="16"
                  ></SvgIcon>
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="taskName"
              label="任务名称"
              width="auto"
            ></el-table-column>
            <!-- <el-table-column prop="nodeStatusName" label="当前节点" width="180">
              <template #default="{ row }">
                <span>
                  {{ !row.nodeStatusCode ? "未开始" : row.nodeStatusName }}
                </span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="处理人" width="140">
              <template #default="{ row }">
                <span class="text--info">
                  {{ row.curHandleUserName }}
                </span>
              </template>
            </el-table-column> -->
            <el-table-column label="启动时间" width="310"
              ><template #default="{ row }">
                <span class="text--info">
                  {{ row.beginTime }}
                </span>
              </template></el-table-column
            >
            <el-table-column label="完成量/启动量" width="170">
              <template #default="{ row }">
                <span
                  class="text--info"
                  @click="handleList(row)"
                  style="color: #5298ff; cursor: pointer"
                >
                  {{ row.insFinishTimes }}/{{ row.insTimes }}
                </span>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                  <el-button
                    type="text"
                    v-auth="`/projectsB/matters--start`"
                    @click="showStartMessageBox(row)"
                    >启动</el-button
                  >
                  <el-button
                    type="text"
                    class="btns-danger"
                    v-auth="`/projectsB/matters--delete`"
                    @click="showDeleteMessageBox(row)"
                    v-if="row.insTimes == 0"
                    >删除</el-button
                  >
                  <!-- <el-button
                    v-if="row.nodeStatusCode"
                    type="text"
                    @click="handleView(row)"
                    v-auth="`/projectsB/matters--look`"
                    >查看</el-button
                  > -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-collapse-transition>
    </el-card>
    <el-dialog
      title="选择人员"
      v-model="dialogVisibleTransferAdd"
      width="920px"
    >
      <add-user
        v-model:dialogVisibleTransferAdd="dialogVisibleTransferAdd"
        :currentUsers="acceptUsers"
        :isSingle="true"
        @emitAddUser="emitAddUser"
      />
    </el-dialog>
    <el-dialog
      title="查看详情"
      v-model="dialogVisibleDetail"
      width="1000px"
      destroy-on-close
    >
      <approval-content
        :contractId="businessId"
        :nodeDefId="nodeDefId"
        :isEdit="false"
        :flowType="flowType"
      >
      </approval-content>
    </el-dialog>

    <el-dialog
      v-model="showCheckList"
      title="检查列表"
      width="70%"
      destroy-on-close
      custom-class="check-list"
      @close="getStageData"
    >
      <detail-list :checkItem="checkItem"></detail-list>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { reactive, ref, defineComponent, toRefs } from "vue";
import {
  templateTaskList,
  storageFlowdata,
  taskDelete,
  proTmpStageList
} from "/@/api/projects";
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
import { ElMessageBox } from "element-plus";
import AddUser from "../../../projectsA/acceptance/concealed/components/dialog/AddUser.vue";
import ApprovalContent from "../../../approval/detail/content.vue";
import SvgIcon from "/@/components/SvgIcon/index.vue";
import detailList from "../../components/detailList.vue";
import { clickEvent } from "/@/utils/func";
import { useRouter } from "vue-router";
export default defineComponent({
  components: { AddUser, ApprovalContent, detailList, SvgIcon },
  setup() {
    let stageId = ref();
    let stageList = ref([]);
    const router = useRouter();
    let params = reactive({
      projectId: storageLocal.getItem("projectInfo")?.id,
      projectStageId: stageId.value,
      pageNum: 1,
      pageSize: 0
    });
    let tableData = ref([]);
    let loading = ref<boolean>(false);
    let total = ref<number>(0);
    const checkItem = ref({}) as any;
    const showCheckList = ref<boolean>(false);
    let state = reactive({
      dialogVisibleTransferAdd: false, // 添加成员弹窗是否显示
      acceptUsers: [],
      taskInfo: {} as any,
      dialogVisibleDetail: false, // 查看页面是否显示
      businessId: 0,
      nodeDefId: "ACT_010",
      activeStage: 0,
      flowType: ""
      // showConfirm: false,
      // delConfirmtext: "确认删除该条记录吗？",
      // startConfirm: false,
      // startConfirmtext: "确认删除该条记录吗？"
    });

    const handleList = row => {
      checkItem.value = row;
      showCheckList.value = true;
    };

    const getStageData = async () => {
      let params = {
        projectId: storageLocal.getItem("projectInfo")?.id,
        pageNum: 1,
        pageSize: 0
      };
      const { code, data } = await proTmpStageList({ ...params });

      if (code === 200) {
        const index = state.activeStage;
        stageId.value = data.list[index] && data.list[index].id;
        stageList.value = data.list || [];
        getTableData({ projectStageId: stageId.value });
      }
    };

    const getTableData = async param => {
      param = Object.assign({}, params, param);
      const { code, data } = await templateTaskList({ ...param });
      if (code === 200) {
        tableData.value = data.list;
        total.value = data.rows;
        if (tableData.value?.length) {
          const success = tableData.value.filter(
            item => item.nodeStatusCode === "end"
          );
          const completePercent = Number(
            ((success.length / tableData.value?.length) * 100).toFixed(0)
          );
          stageList.value[state.activeStage]["completePercent"] =
            completePercent;
        }
      }
    };

    getStageData();

    const handleChange = (item, index) => {
      console.log(item, index);
      state.activeStage = index;
      getStageData();
    };

    const handleView = row => {
      state.businessId = row.businessId;
      state.nodeDefId = row.nodeStatusCode.toUpperCase() || "ACT_010";
      state.flowType = row.flowTypeCode;
      state.dialogVisibleDetail = true;
    };

    const showStartMessageBox = row => {
      let times = row.insTimes + 1;
      ElMessageBox.confirm(`确定要第${times}次开启本事项吗？`, "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        iconClass: "el-icon-question"
      })
        .then(() => {
          handleStart(row);
        })
        .catch(() => {});
    };

    const showDeleteMessageBox = row => {
      ElMessageBox.confirm("确定删除该条记录吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        iconClass: "el-icon-warning"
      })
        .then(() => {
          handleDel(row);
        })
        .catch(() => {});
    };

    const handleStart = row => {
      state.dialogVisibleTransferAdd = true;
      state.taskInfo = row;
    };

    const emitAddUser = async user => {
      state.dialogVisibleTransferAdd = false;
      try {
        const name = storageLocal.getItem("projectInfo")?.name;
        const id = storageLocal.getItem("projectInfo")?.id;
        const params = {
          formBaseInfo: {
            deviceTaskName: `${state.taskInfo.taskName}`,
            billName: `[${state.taskInfo.taskName}]的审批流程`,
            projectName: name,
            projectManageId: id,
            contractName: "", // 无返回
            contractId: 5, // 无返回
            contractNum: "", // 无返回
            partyA: "", // 无返回
            directorAName: "", // 无返回
            directorA: "", // 无返回
            directorBId: "", // 无返回
            partyB: "", // 无返回
            directorBName: "", // 无返回
            remarks: "",
            flowStartAttachmentArr: [],
            id: null
          },
          formSubMap: {
            taskId: state.taskInfo.id,
            flowType: state.taskInfo.approvalNodeCode,
            assignee: user.idList[0].id,
            opinion: "",
            valueJson: ""
          },
          flowFormData: {
            approvalComments: state.taskInfo.approvalComments,
            approvalForm: state.taskInfo.approvalForm,
            // formAttachment: state.taskInfo.approvalNodeTmpAttachment,
            formAttachment: "", // 用户上传时的附件字段
            templateAttachment: state.taskInfo.approvalNodeTmpAttachment, // 模板附件字段
            remarks: state.taskInfo.remarks
          }
        };
        const { code, message } = await storageFlowdata(params);
        if (code === 200) {
          clickEvent("项目事项", "启动", "启动B类事项审批");
          NotifMessage.success(message);
          // 刷新本页面
          getStageData();
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const handleDel = async row => {
      try {
        const { code, message } = await taskDelete({ id: row.id });
        if (code === 200) {
          NotifMessage.success(message);
          clickEvent("项目事项", "删除", "删除B类事项");
          getStageData();
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const goBack = () => {
      router.push(`/projects/manage/space`);
    };

    const tableRowClassName = ({ rowIndex }) => {
      if (rowIndex % 2 == 1) {
        return "odd-row";
      } else {
        return "";
      }
    };

    return {
      ...toRefs(state),
      tableData,
      loading,
      total,
      showCheckList,
      stageList,
      checkItem,
      handleView,
      handleStart,
      emitAddUser,
      handleList,
      handleDel,
      handleChange,
      showStartMessageBox,
      showDeleteMessageBox,
      tableRowClassName,
      getStageData,
      goBack
    };
  }
});
</script>
<style>
.el-icon-question {
  color: #ffc069;
}
.el-icon-warning {
  color: #e45d5d !important;
}
</style>

<style lang="scss" scoped>
.list-page :deep .el-dialog .form__footer {
  text-align: right;
}
.stage-box {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 102px;
  &::after {
    position: absolute;
    content: "";
    width: 100%;
    height: 5px;
    bottom: 0;
    background: rgba(228, 232, 242, 0.5);
  }
  &:last-child {
    display: none;
  }
  .text-box {
    display: flex;
    align-items: center;
    width: 174px;
    height: 100%;
    border-bottom: 5px solid transparent;
    z-index: 10;
    cursor: pointer;
    &.active {
      border-color: #8895b7;
    }
    &.hasState {
      &.active {
        border-color: #5298ff;
      }
      .p-box {
        color: #5298ff;
        background: rgba(82, 152, 255, 0.1);
      }
      .status-box {
        background: rgba(82, 152, 255, 0.3);
        border-color: rgba(82, 152, 255, 0.3);
      }
    }
    &.complete {
      &.active {
        border-color: #85df00;
      }
      .p-box {
        color: #85df00;
        background: rgba(133, 223, 0, 0.1);
      }
      .status-box {
        background: #ffffff;
        border: 1px solid #f2fbe5;
      }
    }

    .p-box {
      flex-shrink: 0;
      width: 56px;
      height: 56px;
      background: rgba(136, 149, 183, 0.1);
      text-align: center;
      border-radius: 50%;
      font-size: 0;
      line-height: 0;
      color: #8895b7;
      font-weight: bold;
      p {
        font-size: 18px;
        line-height: 25px;
        margin-top: 13px;
      }
      span {
        display: inline-block;
        font-size: 12px;
        margin-top: 2px;
      }
    }
    .status-box {
      display: flex;
      align-items: center;
      min-width: 115px;
      height: 24px;
      background: #fff;
      border-radius: 12px;
      border: 1px solid #edf4ff;
      margin-left: 5px;
      i {
        font-size: 24px;
      }
      .text {
        font-weight: bold;
        margin-left: 5px;
        color: #494c53;
        font-size: 14px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
  .arrow-box {
    width: 64px;
    &.hide {
      display: none;
    }
    i {
      font-size: 20px;
      color: #e4e8f2;
      margin-left: -10px;
      &:first-child {
        margin-left: 0;
      }
    }
  }
}
.btm-table::after {
  // display: block;
  // content: "";
  // bottom: 0;
  // height: 5px;
  // background: rgba(228, 232, 242, 0.5);
}
:deep .el-table__row.odd-row {
  background: #fdfdff;
}
</style>
